package org.web.common.sso.server.biz;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.web.base.domain.ResultDO;
import org.web.base.domain.exception.ResultMessageEnum;
import org.web.base.domain.helper.ResultHelper;
import org.web.common.sso.server.config.SSOServerConfig;
import org.web.common.sso.server.controller.info.SsoMessageInfoEnum;
import org.web.common.sso.server.helper.SSOServerConstant;
import org.web.common.sso.server.helper.redis.CacheSessionDO;

import javax.annotation.Resource;

@Service("tokenBiz")
public abstract class AbstractTokenBiz implements SSOServerConstant {


    @Resource
    private SSOServerConfig ssoServerConfig;



    /***
     * 支持从缓存获取以及从数据库中获取token信息。
     * */
    public ResultDO<CacheSessionDO> getAndRefreshCacheSessionDO(String token) {
        ResultDO<CacheSessionDO> resultDO = new ResultDO<>();
        CacheSessionDO cacheSessionDO;
        if (StringUtils.isEmpty(token)) {
            ResultHelper.buildResultDOByResultMessageEnum(resultDO, ResultMessageEnum.PARAM_EMPTY, SsoMessageInfoEnum.getSessionByToken_token_missing.getMessage(), null);
            return resultDO;
        }

        resultDO = exchangeToken(token);

        if (resultDO != null && resultDO.isFailed()) {
            return resultDO;
        }
        cacheSessionDO = resultDO.getDomain();

        // refresh cache, 减少更新次数，做了优化处理。
        long inCashTime = System.currentTimeMillis() - cacheSessionDO.getLastMarkTime();
        if (inCashTime > ssoServerConfig.getRefreshInCashTime() * ONE_MINUTE_THOUSANDTH) {
            cacheSessionDO.setLastMarkTime(System.currentTimeMillis());
            // 数据库update-time等同于放入缓存lastMark-time。
            refreshToken(token, cacheSessionDO);
        }
        resultDO.setDomain(cacheSessionDO);
        return resultDO;
    }

    public abstract ResultDO<CacheSessionDO> exchangeToken(String token);

    public abstract void refreshToken(String token, CacheSessionDO cacheSessionDO);

}
